package com.haizhi.util;


import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpRequests {

    private static Logger logger = LoggerFactory.getLogger(HttpRequests.class);

    // utf-8字符编码
    private static final String CHARSET_UTF_8 = "utf-8";

    // HTTP内容类型。
    private static final String CONTENT_TYPE_TEXT_HTML = "text/xml";

    // HTTP内容类型。相当于form表单的形式，提交数据
    private static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";

    // HTTP内容类型。相当于form表单的形式，提交数据
    private static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";

    // 请求配置
    private static RequestConfig requestConfig;

    static {

        try {
            org.apache.http.ssl.SSLContextBuilder builder = org.apache.http.ssl.SSLContextBuilder.create();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    builder.build());
            // 配置同时支持 HTTP 和 HTPPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                    "http", PlainConnectionSocketFactory.getSocketFactory()).register(
                    "https", sslsf).build();

            // 根据默认超时限制初始化requestConfig
            int socketTimeout = 50000;
            int connectTimeout = 50000;
            int connectionRequestTimeout = 50000;
            requestConfig = RequestConfig.custom().
                    setConnectionRequestTimeout(connectionRequestTimeout).
                    setSocketTimeout(socketTimeout).
                    setConnectTimeout(connectTimeout).build();

        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            logger.error("ERROR:", e);
        }

    }

    private static CloseableHttpClient getHttpClient() {

        return HttpClients.custom()
                // 设置请求配置
                .setDefaultRequestConfig(requestConfig)
                // 设置重试次数
                .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
                .build();
    }

    /**
     * 发送Get请求
     *
     * @param httpRequestBase httpRequestBase
     * @return String
     */
    private static String sendRequest(HttpRequestBase httpRequestBase) {

        CloseableHttpClient httpClient;
        CloseableHttpResponse response = null;
        // 响应内容
        String responseContent;
        try {
            // 创建默认的httpClient实例.
            httpClient = getHttpClient();

            // 配置请求信息
            httpRequestBase.setConfig(requestConfig);

            // 执行请求
            response = httpClient.execute(httpRequestBase);

            // 得到响应实例
            HttpEntity entity = response.getEntity();

            // 判断响应状态
            if (response.getStatusLine().getStatusCode() >= 300) {
                logger.error("HTTP Request is not success, Response code is {}", response.getStatusLine().getStatusCode());
                //throw new Exception("HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
                return null;
            }

            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
                EntityUtils.consume(entity);
            } else {
                return null;
            }

        } catch (Exception e) {
            logger.error("ERROR:", e);
            return null;
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("ERROR:", e);
            }
        }
        return responseContent;
    }


    /**
     * 发送 post请求
     *
     * @param httpUrl 地址
     */
    public static String post(String httpUrl) {
        // 创建httpPost
        HttpPost httpPost = new HttpPost(httpUrl);
        return sendRequest(httpPost);
    }

    /**
     * 发送 get请求
     *
     * @param httpUrl 访问地址
     */
    public static String get(String httpUrl) {
        // 创建get请求
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendRequest(httpGet);
    }


    /**
     * 发送 post请求（带文件）
     *
     * @param httpUrl   地址
     * @param maps      参数
     * @param fileLists 附件
     */
    public static String post(String httpUrl, Map<String, String> maps, List<File> fileLists) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
        if (maps != null) {
            for (String key : maps.keySet()) {
                meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
            }
        }
        if (fileLists != null) {
            for (File file : fileLists) {
                FileBody fileBody = new FileBody(file);
                meBuilder.addPart("file", fileBody);
            }
        }
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        return sendRequest(httpPost);
    }

    /**
     * 发送 post请求（单个文件）
     *
     * @param httpUrl 地址
     * @param md5     文件MD5
     * @param file    传输文件
     */
    public static String post(String httpUrl, String md5, File file) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();

        FileBody fileBody = new FileBody(file);
        meBuilder.addPart("file", fileBody);

        httpPost.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
        httpPost.setHeader(HttpHeaders.CONTENT_MD5, md5);
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        return sendRequest(httpPost);
    }

    /**
     * 发送 post请求
     *
     * @param maps 参数
     */
    public static String post(String httpUrl, Map<String, String> maps) {
        String param = convertStringParam(maps);
        return post(httpUrl, param, CONTENT_TYPE_FORM_URL);
    }


    /**
     * 发送 post请求 发送json数据
     *
     * @param httpUrl    地址
     * @param paramsJson 参数(格式 json)
     */
    public static String post(String httpUrl, String paramsJson, String contentType) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        try {
            // 设置参数
            if (paramsJson != null && paramsJson.trim().length() > 0) {
                StringEntity stringEntity = new StringEntity(paramsJson, CHARSET_UTF_8);
                stringEntity.setContentType(contentType);
                httpPost.setEntity(stringEntity);
            }
        } catch (Exception e) {
            logger.error("ERROR:", e);
        }
        return sendRequest(httpPost);
    }


    /**
     * 将map集合的键值对转化成：key1=value1&key2=value2 的形式
     *
     * @param parameterMap 需要转化的键值对集合
     * @return 字符串
     */
    private static String convertStringParam(Map parameterMap) {
        StringBuilder parameterBuffer = new StringBuilder();
        if (parameterMap != null) {
            Iterator iterator = parameterMap.keySet().iterator();
            String key;
            String value;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                if (parameterMap.get(key) != null) {
                    value = (String) parameterMap.get(key);
                } else {
                    value = "";
                }
                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }
        return parameterBuffer.toString();
    }

    /**
     * 下载文件
     *
     * @param url          http://www.xxx.com/img/333.jpg
     * @param destFilePath xxx.jpg/xxx.png/xxx.txt
     * @throws IOException
     */
    public static boolean getFile(String url, String destFilePath) {
        // 生成一个httpclient对象
        int l;
        byte[] tmp = new byte[1024 * 4];
        CloseableHttpClient httpclient = getHttpClient();
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response;
        try {
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            File file = new File(destFilePath);
            logger.info("存储文件位置: {}", destFilePath);
            try (InputStream in = entity.getContent()) {
                FileOutputStream out = new FileOutputStream(file);
                while ((l = in.read(tmp)) != -1) {
                    out.write(tmp, 0, l);
                }
                out.flush();
                out.close();
            }
            response.close();
            // 关闭低层流。
            httpclient.close();
        } catch (IOException e) {
            logger.error("ERROR:", e);
            return false;
        }

        return true;
    }


    public static void main(String[] args) throws Exception {
        logger.info(get("http://www.baidu.com"));
    }
}